<template>
  <div>
      <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/main/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/UserManagement'}">用户管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/RoleManagement'}">角色管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/MenuManagement'}">菜单管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{path:'/main/CompanyManagement'}">公司管理</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form :inline="true" :model="formData">
          <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="formData.username" clearable @clear="queryList"/>
          </el-form-item>
          <el-form-item label="手机号">
          <el-input placeholder="请输入手机号" v-model="formData.mobile" clearable @clear="queryList"/>
          </el-form-item>
          <el-form-item >
              <el-button type="primary" @click="queryList">搜索</el-button>
              <el-button type="primary" @click="add1" :title="title">新增用户</el-button>
              <el-button type="danger" @click="removBatch">批量删除</el-button>
          </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%"  @selection-change="handleSelectionChange" ref="multipleTableRef">
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column prop="mobile" label="手机号" width="150"/>
      <el-table-column prop="nickname" label="昵称" width="150" />
      <el-table-column prop="email" label="邮箱" width="150"/>
      <el-table-column prop="status" label="状态" width="100" >
        <template #default="scope">
          <el-tag v-if="scope.row.status == 1">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status == 2">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作" >
        <template #default="scope">
          <el-button size="mini" type="primary" :title="title" @click="edit1(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="remove(scope.row.id)" >删除</el-button>
        </template>
      </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
          <div class="demonstration"></div>
          <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="sizes, prev, pager, next"
          :total="1000"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          />
      </div>

      <el-dialog v-model="dialogFormVisible" :title="title" width="500" @close="cancel" >
        <el-form :model="form">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input v-model="userData.username" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth">
            <el-input v-model="userData.mobile" placeholder="请输入手机号"/>
          </el-form-item>
          <el-form-item label="昵称" :label-width="formLabelWidth">
            <el-input v-model="userData.nickname" placeholder="请输入昵称"/>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth">
            <el-input v-model="userData.email" placeholder="请输入邮箱"/>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input v-model="userData.userpwd" show-password placeholder="请输入密码"/>
          </el-form-item>
          <el-form-item label="状态" :label-width="formLabelWidth">
              <el-cascader :options="options" placeholder="请选择状态"  v-model="userData.status"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancle">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
          </div>
        </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref,onMounted,getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';

const currentInstance = getCurrentInstance()
const {$http}=currentInstance.appContext.config.globalProperties;
const tableData= ref([])
const dialogFormVisible = ref(false)
let title = ref()
const options = [
{
  value: '1',
  label: '可用',
  disabled: false,
},
{
  value: '2',
  label: '不可用',
  disabled: false,
}
]


//批量删除
const selectable = (row) => ![].includes(row.id)
const handleSelectionChange = (val) => {
formData.value.ids = val.map(item => item.id);
}

const formData = ref({
roleCode:'',
roleName:'',
pageNum:1,
pageSize:5,
ids:[]
})

const userData= ref({
id:'',
username:'', 
mobile:'', 
nickname:'',
email:'',
userpwd:'',
salt:'',
status:'1'
})



onMounted(()=>{
queryList();
});

function handleSizeChange(val) {
    formData.value.pageSize=val
    queryList();
}
function handleCurrentChange(val) {
    formData.value.pageNum=val
    queryList();
}



// 查
function queryList(){
$http({
  method:'get',
  url:'http://localhost:8081/sfzy/sysUser/page',
  params:formData.value
}).then(res=>{
  tableData.value = res.data.data.list;
})
}
// 批量删  
function removBatch(){
      ElMessageBox.confirm('是否确认删除选中的数据?', '删除', 
          {
          confirmButtonText: '确认', // 确认按钮
          cancelButtonText: '取消', // 取消按钮
          type: 'warning',// 警告的图标
          }
      )
      .then(() => {
        const idsArray = formData.value.ids;
        const idsStr = idsArray.join(",");
        
         // 点击确认 删除操作
          $http({
              method:'delete',
              url:`http://localhost:8081/sfzy/sysUser?ids=${idsStr}`,
              data:{}
          }).then(res=>{
              if(res.status== 200){
                  ElMessage.success('删除成功')
                  // 判断当前页是否还有数据，如果没有则将页码减1
                  if (tableData.value.length === 0 && formData.value.pageNum > 1) {
                   formData.value.pageNum--;
              }
              // 清理ids参数
              formData.value.ids = [];
                  queryList();
              }else{
                  ElMessage.error('删除失败')
              }
          })
      })
      .catch(() => {
          ElMessage({
              type: 'info',
              message: "取消删除操作",
          })
})}
// id删        
function remove(id){
      ElMessageBox.confirm('是否确认删除选中的数据?', '删除', 
          {
          confirmButtonText: '确认', // 确认按钮
          cancelButtonText: '取消', // 取消按钮
          type: 'warning',// 警告的图标
          }
      )
      .then(() => {
         // 点击确认 删除操作
          $http({
              method:'delete',
              url:`http://localhost:8081/sfzy/sysUser/${id}`,
               params:{}
          }).then(res=>{
              if(res.status== 200){
                  ElMessage.success('删除成功')
                  queryList();
              }else{
                  ElMessage.error('删除失败')
              }
          })
      })
      .catch(() => {
          ElMessage({
              type: 'info',
              message: "取消删除操作",
          })
     })}
// 新增
function add1(){
title.value = '新增用户'
dialogFormVisible.value=true
options[1].disabled=true
}

function add(){
      $http({
          method:'post',
          url:'http://localhost:8081/sfzy/sysUser',
          data:userData.value
      }).then(res=>{
          if(res.data.code== 200){
            ElMessage.success('添加成功')
            // const userId = res.data.data;  
            // integral(userId)
            // sysUserRole(userId)
          }else{
              ElMessage.success('添加失败')
          }
          //关闭添加 对话框
          dialogFormVisible.value= false;
          // 在做一次查询
          queryList();
          cancle();
        })
}

// function integral(userId){
//           const integralData={
//               userId:userId,
//               integrals: 10
//             }
//         $http({
//             method:'post',
//             url:'http://localhost:8081/sfzy/integral',
//             data:integralData
//         }).then(res=>{
//             if(res.data.code== 200){
//                 ElMessage.success('添加成功')
//             }else{
//                 ElMessage.success('添加失败')
//             }
//             //关闭添加 对话框
//             dialogFormVisible.value= false;
//             // 在做一次查询
//             queryList();
//             cancle();
//           })
// }
// function sysUserRole(userId){
//   const sysUserRoleData={
//               userId:userId,
//               roleId:1
//             }
//         $http({
//             method:'post',
//             url:'http://localhost:8081/sfzy/sysUserRole',
//             data:sysUserRoleData
//         }).then(res=>{
//             if(res.data.code== 200){
//                 ElMessage.success('添加成功')
//             }else{
//                 ElMessage.success('添加失败')
//             }
//             //关闭添加 对话框
//             dialogFormVisible.value= false;
//             // 在做一次查询
//             queryList();
//             cancle();
//           })
// }





// 修改
function edit1(rowData){
title.value = '修改用户'
dialogFormVisible.value=true
options[1].disabled=false
userData.value=rowData
}

function edit(){
      $http({
          method:'put',
          url:'http://localhost:8081/sfzy/sysUser',
          data:userData.value
      }).then(res=>{
          if(res.data.code== 200){
              ElMessage.success('修改成功')
          }else{
              ElMessage.success('修改失败')
          }
          //关闭添加 对话框
          dialogFormVisible.value= false;
          // 在做一次查询
          queryList();
          cancle();
        })
}

function confirm(){
if(title.value=='新增用户'){
  add();
}else{
  edit();
}
}

//关闭
function cancle(){
dialogFormVisible.value = false;
      userData.value = {
        id:'',
      username:'', 
      mobile:'', 
      nickname:'',
      email:'',
      userpwd:'',
      salt:'0',
      status:'1'
      }
      queryList();
}
</script>

<style scoped>

</style>
